package org.star.dolphin.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SecurityUtil {

    /**
     * 加密
     *
     * @param str
     * @param charsetName
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String encoder(String str, String charsetName) throws NoSuchAlgorithmException,
            UnsupportedEncodingException {
        return DigestUtils.md5Hex(str.getBytes(charsetName));
    }

    /**
     * 计算文件md5值
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String encoder(InputStream is) throws IOException {
        return DigestUtils.md5Hex(is);
    }

    /**
     * SHA1编码/加密
     *
     * @param input
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encoderSHA1(byte[] input) throws NoSuchAlgorithmException {
        MessageDigest mDigest = MessageDigest.getInstance("SHA1");
        byte[] result = mDigest.digest(input);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < result.length; i++) {
            sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }
}
